/**
 * Copyright (c) 2025   All rights reserved.
 * <p>
 * https://www.sdl.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.sdl.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.sdl.common.exception.ErrorCode;
import io.sdl.common.exception.RenException;
import io.sdl.common.service.impl.BaseServiceImpl;
import io.sdl.common.validator.AssertUtils;
import io.sdl.dao.UserDao;
import io.sdl.dto.LoginDTO;
import io.sdl.dto.UpdateUserDTO;
import io.sdl.entity.TokenEntity;
import io.sdl.entity.UserEntity;
import io.sdl.service.TokenService;
import io.sdl.service.UserService;
import io.sdl.common.utils.UploadFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends BaseServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    private TokenService tokenService;


    // 文件存储根路径
    @Value("${file.upload-dir}")
    private String uploadDirResource;

    @Override
    public UserEntity getByMobile(String mobile) {
        return baseDao.getUserByMobile(mobile);
    }

    @Override
    public UserEntity getUserByUserId(Long userId) {
        return baseDao.getUserByUserId(userId);
    }

    @Override
    public Map<String, Object> login(LoginDTO dto) {
        UserEntity user = getByMobile(dto.getMobile());
        AssertUtils.isNull(user, ErrorCode.ACCOUNT_PASSWORD_ERROR);

        //密码错误
        if (!user.getPassword().equals(DigestUtil.sha256Hex(dto.getPassword()))) {
            throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
        }

        //获取登录token
        TokenEntity tokenEntity = tokenService.createToken(user.getId());

        Map<String, Object> map = new HashMap<>(2);
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireDate().getTime() - System.currentTimeMillis());

        return map;
    }


    //查询/新增用户
    @Override
    public Map<String, Object> findOrCreateUser(UserEntity user) {

        //查询用户信息
        UserEntity userInfo = baseDao.findUserByOpenid(user.getOpenId());
        Date now = new Date();
        Long userId;
        //创建用户
        if(userInfo==null){
            user.setId(IdWorker.getId());
            user.setUsername("用户"+new Date().getTime());
            user.setCreateDate(now);
            user.setLastLogin(now);
            user.setLoginCount(1);
            baseDao.addUser(user);
            userId=user.getId();

        }else{
            userId=userInfo.getId();

            LambdaUpdateWrapper<UserEntity> updateWrapper = new LambdaUpdateWrapper<>();

            updateWrapper.eq(UserEntity::getId, userId);
            updateWrapper.set(UserEntity::getLastLogin, now);
            updateWrapper.set(UserEntity::getLoginCount, userInfo.getLoginCount()+1);//查询到的用户登录次数+1
//            updateWrapper.set(UserEntity::getAvatarUrl, user.getAvatarUrl());
            if(userInfo.getLoginCount() == 1 ){
                updateWrapper.set(UserEntity::getNickName, user.getNickName());
            }

            //记录登录次数和最后登录时间
            baseDao.update(updateWrapper);
        }

        //获取登录token
        TokenEntity token = tokenService.createToken(userId);
        //token续期
        tokenService.expireToken(token.getUserId(),true);
        Map<String, Object> map = new HashMap<>(2);
        map.put("token", token.getToken());
        map.put("expire", token.getExpireDate().getTime() - System.currentTimeMillis());
        map.put("userId", userId);
        return map;
    }

    @Override
    public void saveUserInfo(UpdateUserDTO user) {
        //获取当前用户的手机号
        TokenEntity byToken = tokenService.getByToken(user.getToken());

        LambdaUpdateWrapper<UserEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserEntity::getId, byToken.getUserId());
        updateWrapper.set(UserEntity::getNickName, user.getNickName());
        updateWrapper.set(UserEntity::getGender, user.getGender());
        updateWrapper.set(UserEntity::getBirthday, user.getBirthday());
        updateWrapper.set(UserEntity::getCity, user.getCity());
        updateWrapper.set(UserEntity::getUsername, user.getUsername());
        baseDao.update(updateWrapper);
    }

    @Override
    public Integer saveUploadedFile(MultipartFile file, Long id) {
        try {

            String accessUrl = "/uploads/" + UploadFileUtils.uploadFile(file);

            UserEntity userEntity = baseDao.selectById(id);
            userEntity.setAvatarUrl(accessUrl);

            return baseDao.updateById(userEntity);
        } catch (IOException e) {
            throw new RuntimeException("文件存储失败", e);
        }
    }

    @Override
    public UserEntity passWordLogin(String account, String password) {


        return baseDao.passWordLogin(account,password);
    }

}